package com.zl.learning.thread;

import java.util.concurrent.*;

public class ThreadTest {
    public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {

            }
        });
        System.out.println(t1.getClass());

        Thread t2 = new Thread() {
            @Override
            public void run() {
                super.run();
            }
        };
        System.out.println(t2.getClass());
    }

    public static class Test1 {
        private static final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();

        public static void main(String[] args) {
            final ExecutorService executorService = Executors.newCachedThreadPool();
            executorService.execute(() -> {
                boolean start = true;
                while (start) {
                    final String take;
                    try {
                        take = queue.take();
                        System.out.println(take);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        start = false;
                    }
                }
            });

            executorService.shutdownNow();
        }
    }

    public static class Test2 {

        private static final ExecutorService executorService = Executors.newCachedThreadPool();

        public static void main(String[] args) throws ExecutionException, InterruptedException {
            BlockingQueue<Integer> blockingQueue = new LinkedBlockingDeque<>(10);
            final Future<Long> future = executorService.submit(() -> sum(blockingQueue));
            for (int i = 0; i < 20; i++) {
                try {
                    blockingQueue.put(i);
                    System.out.println(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(future.get());
        }

        private static Long sum(BlockingQueue<Integer> queue) {
            boolean start = true;
            long sum = 0;
            while (start) {
                try {
                    Integer val = queue.poll(100, TimeUnit.SECONDS);
                    TimeUnit.SECONDS.sleep(3);
                    if (val != null) {
                        sum += val;
                    } else {
                        start = false;
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    start = false;
                }
            }
            return sum;
        }


    }
}
